package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService  dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @return
     */
@PostMapping
    public R<String> save(@RequestBody DishDto dishDto){

    log.info(dishDto.toString());
    dishService.saveWithFlavor(dishDto);


    //当新增菜品后，精确清理当前菜品在Redis下缓存的数据
    String key="dish_"+dishDto.getCategoryId()+"_1";
    redisTemplate.delete(key);

    return R.success("新增菜品成功");
    }

    /**
     * 查询菜品
     * @return
     */
    @GetMapping("/page")
    public  R<Page> page(int page, int pageSize, String name){

        //构造分页构造器
        Page<Dish> pageInfo = new Page(page, pageSize);

        Page<DishDto> dishDtoPage=new Page<>();
        //构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo,queryWrapper);

        //通过id去查询菜品分类,进行对象值拷贝，pageInfo里面分页信息传给dishDtoPage
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");//忽略这个属性
        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list=records.stream().map((item)->{
            DishDto dishDto = new DishDto();
            //复制参数数值给dishDto
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//获取分类id
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
          dishDtoPage.setRecords(list);
        //页面图片由文件下载功能实现
        return R.success(dishDtoPage);
    }

    /**
     * 根据id回显菜品信息
     */
    @GetMapping("/{id}")
    public  R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }
    /**
     * 保存修改菜品
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){

        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        //当菜品发生修改后，精确清理当前菜品在Redis下缓存的数据
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);


        return R.success("修改菜品成功");
    }

    /**
     * 根据菜品属性  查出菜品
     *用Dto做参数，完成代码复用于用户界面显示菜品信息和口味
     * 涉及三表查询，Dish，DishFlavor，Category
     */
    @GetMapping("/list")
    public R<List<DishDto>> list( Dish dish){

        List<DishDto> dishDtoList=null;


        //从Redis中获取缓存数据，Key设置为  dish_1397844303408574465_1
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);

        if(dishDtoList!=null){
            //如果存在数据，直接返回数据
            return R.success(dishDtoList);
        }

        //菜品分类id相同传入list集合
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //菜品排序
         queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list= dishService.list(queryWrapper);

           dishDtoList=list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            //复制参数数值给dishDto
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//获取分类id
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //获取当前菜品Id，查询对应的口味数据
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor>  dishFlavorLambdaQueryWrapper= new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

       //不存在则从数据库返回数据额，并缓存在redis数据库中；设置60分钟过期
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);


        return R.success(dishDtoList);
    }
}
